"use client"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { signIn } from "next-auth/react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { useState } from "react"

export default function LoginPage() {
  const router = useRouter()
  const [error, setError] = useState<string>("")
  const [loading, setLoading] = useState(false)

  async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault()
    setLoading(true)
    setError("")

    try {
      const formData = new FormData(event.currentTarget)
      const response = await signIn("credentials", {
        username: formData.get("username"),
        password: formData.get("password"),
        redirect: false,
      })

      if (response?.error) {
        setError("用户名或密码错误")
        setLoading(false)
        return
      }

      // 登录成功，重定向到首页
      router.push("/")
      router.refresh()
      
    } catch (error) {
      setError("登录过程中发生错误")
    } finally {
      setLoading(false)  // 确保无论成功还是失败都重置loading状态
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center">
      <div className="w-full max-w-md space-y-8 px-4">
        <div className="text-center">
          <h1 className="text-2xl font-bold">登录</h1>
          <p className="mt-2 text-gray-600">欢迎回来</p>
        </div>

        <form onSubmit={onSubmit} className="space-y-4">
          <div>
            <Input
              name="username"
              type="text"
              placeholder="用户名"
              required
              disabled={loading}
            />
          </div>

          <div>
            <Input
              name="password"
              type="password"
              placeholder="密码"
              required
              disabled={loading}
            />
          </div>

          {error && (
            <p className="text-sm text-red-500">{error}</p>
          )}

          <Button
            type="submit"
            className="w-full"
            disabled={loading}
          >
            {loading ? "登录中..." : "登录"}
          </Button>

          <p className="text-center text-sm text-gray-600">
            还没有账号？{" "}
            <Link href="/auth/register" className="text-blue-600 hover:underline">
              注册
            </Link>
          </p>
        </form>
      </div>
    </div>
  )
} 